/* 
 * File:   widget_curve_mouse.cpp
 * Author: dima
 * 
 * Created on 15 Январь 2015 г., 12:06
 */
#include <QMouseEvent>
#include "widget_curve_mouse.h"
#include <qwt_plot_picker.h>
#include <qwt_picker_machine.h>

widget_curve_mouse::widget_curve_mouse(QWidget *widget) : widget_curve(widget)
{
    init_window();
}

widget_curve_mouse::widget_curve_mouse(const QwtText &title, QWidget *widget) : widget_curve(title, widget)
{
    init_window();
}

widget_curve_mouse::~widget_curve_mouse()
{
    delete d_picker;
}

double widget_curve_mouse::get_coordinate() const// get the coordinate y
{
    return invTransform(QwtPlot::yLeft, d_picker->trackerPosition().y());
}

void widget_curve_mouse::get_coordinates(double &x, double &y)const // get the coordinates
{
    x = invTransform(QwtPlot::xBottom, d_picker->trackerPosition().x());
    y = invTransform(QwtPlot::yLeft, d_picker->trackerPosition().y());
}

void widget_curve_mouse::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
        find_vertex();
    QwtPlot::mousePressEvent(event);
}

void widget_curve_mouse::mouseMoveEvent(QMouseEvent * event)
{

    if ((event->buttons() & Qt::LeftButton) && current_vertex != -1)
    {
        current_y = get_coordinate();
        Y->operator[](current_vertex) = current_y;
        set_data();
        emit update_data(current_vertex, current_x, current_y);
    }
    QwtPlot::mouseMoveEvent(event);
}

void widget_curve_mouse::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && current_vertex != -1)
        current_vertex = -1;
    QwtPlot::mouseReleaseEvent(event);
}

void widget_curve_mouse::find_vertex() // search vertex
{
    double Eps = 5;
    get_coordinates(current_x, current_y);
    double x_l = current_x - Eps;
    double x_r = current_x + Eps;
    double y_l = current_y - Eps;
    double y_r = current_y + Eps;
    double x, y;
    for (int i = 0; i < X->size(); i++)
    {
        x = X->operator[](i);
        y = Y->operator[](i);
        if ((x <= x_r && x >= x_l) && (y <= y_r && y >= y_l))
        {
            current_vertex = i;
            return;
        }
    }
    current_vertex = -1;
}

void widget_curve_mouse::init_window() // initialization window
{
    current_vertex = -1;
    // display the coordinates of the mouse
    d_picker = new QwtPlotPicker(QwtPlot::xBottom, QwtPlot::yLeft,
                                 QwtPlotPicker::CrossRubberBand,
                                 QwtPicker::ActiveOnly,
                                 this->canvas());

    // Color perpendicular lines
    d_picker->setRubberBandPen(QColor(Qt::red));

    // Color coordinates of the cursor position
    d_picker->setTrackerPen(QColor(Qt::black));

    // Explicit inclusion of the above functions
    d_picker->setStateMachine(new QwtPickerDragPointMachine());
}


